//
//  AppDelegate.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/18.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    /*
    1. 如果没登录 就直接进入主界面
    2. 如果已经登录了 判断是否是新版本,是 就进入欢迎页
    3. 登陆成功后进入欢迎页，之后进入主界面的内容浏览
    */
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.mainScreen().bounds)

        //注册通知的监听者（appDelegate就是监听者）
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootVC:", name: CXSwitchRootVCNotification, object: nil)
        window?.rootViewController = CXUserInfoViewModel.sharedUserModel.isLogin ? viewControllerShouldLoad() : CXMainController()
       // window?.rootViewController = CXNewFeatureController()
        window?.makeKeyAndVisible()
        
        // 保证在程序加载完毕后就创建了数据库文件 这样在使用的时候避免创建文件导致耗时
        SQLiteManager.sharedManager
        
        return true
    }
    ///  修改根控制器  -> 方便登录成功后进入欢迎页
    @objc private func switchRootVC(notifi: NSNotification) {
        if notifi.object != nil {
            window?.rootViewController = CXWelcomeController()
        } else {
            window?.rootViewController = CXMainController()
        }
    }
    ///  返回应该进入的根控制器
    func viewControllerShouldLoad() -> UIViewController{
        
        if isCurrentVersion() {
            return CXWelcomeController()
        } else {
            return CXNewFeatureController()
        }
    }
///  是否是当前版本
    func isCurrentVersion() -> Bool {
        let versionKey = "version"
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey(versionKey) as? String
        if currentVersion == sandboxVersion {
            return true
        }
        //比较完毕后将版本号存入偏好设置
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey)
        return false
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //进入后台。尝试清除 SQLite 缓存
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        
        CXStatusDAL.clearCache()
    }

}

